<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人信息</h2>
        </div>
      </template>

      <div class="avatar-section">
        <el-avatar :size="100" :src="userAvatar">{{ userNameFirst }}</el-avatar>
        <div class="info-section" style="text-align: center">
          <div class="info-item">
            <span class="value">{{ userName }}</span>
          </div>
        </div>
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-button type="primary" class="upload-btn">更换头像</el-button>
        </el-upload>
      </div>

      <div class="password-section">
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitPasswordChange">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import config from "../config";

const userName = computed(() => localStorage.getItem("userName") || "用户");
const userAvatar = ref(localStorage.getItem("userAvatar") || "");
const userNameFirst = computed(() => userName.value.charAt(0));

// 上传相关配置
const uploadUrl = `${config.baseURL}/upload/avatar`; // 替换为实际的上传接口
const headers = {
  Authorization: `Bearer ${localStorage.getItem("token")}`,
};

// 密码表单
const passwordFormRef = ref(null);
const passwordForm = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: "请输入原密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("头像只能是 JPG 或 PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

// 头像上传成功的回调
const handleAvatarSuccess = (response) => {
  userAvatar.value = response.url;
  localStorage.setItem("userAvatar", response.url);
  ElMessage.success("头像更新成功");
};

// 提交密码修改
const submitPasswordChange = async () => {
  if (!passwordFormRef.value) return;

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里替换为实际的密码修改API调用
        // const response = await updatePassword(passwordForm.value)
        ElMessage.success("密码修改成功");
        passwordForm.value = {
          oldPassword: "",
          newPassword: "",
          confirmPassword: "",
        };
      } catch (error) {
        ElMessage.error("密码修改失败：" + error.message);
      }
    }
  });
};
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 40px auto;
  padding: 0 20px;
}

.profile-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
}

.info-item {
  font-size: 16px;
}

.label {
  color: #666;
  margin-right: 10px;
}

.value {
  color: #333;
  font-weight: 500;
}

.password-section {
  max-width: 400px;
  margin: 0 auto;
}

.upload-btn {
  margin-top: 10px;
}

:deep(.el-avatar) {
  background-color: #ff6700;
}
</style> 